package com.suncky.frame.http.interceptor;

import com.suncky.frame.utils.NetworkUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class CacheInterceptor implements Interceptor {

    private final int maxStaleConnected;//秒
    private final int maxStaleUnconnected;//秒

    public CacheInterceptor() {
        this.maxStaleUnconnected = 0;
        this.maxStaleConnected = 0;
    }

    /**
     * 创建缓存数据拦截器
     * @param maxStaleUnconnected 未联网状态下接受的缓存数据的最大时间
     */
    public CacheInterceptor(int maxStaleUnconnected) {
        this.maxStaleUnconnected = maxStaleUnconnected;
        this.maxStaleConnected = 0;
    }

    /**
     * 创建缓存数据拦截器
     *
     * @param maxStaleConnected   联网状态下接受的缓存数据的最大时间
     * @param maxStaleUnconnected 未联网状态下接受的缓存数据的最大时间
     */
    public CacheInterceptor(int maxStaleConnected, int maxStaleUnconnected) {
        this.maxStaleConnected = maxStaleConnected;
        this.maxStaleUnconnected = maxStaleUnconnected;
    }

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (!NetworkUtils.isConnected()) {
            request = request.newBuilder()
                    .cacheControl(new CacheControl
                            .Builder()
                            .maxStale(maxStaleUnconnected, TimeUnit.SECONDS)
//                            .onlyIfCached()
                            .build()
                    )
//                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStaleUnconnected)
                    .build();
        } else {
            request = request.newBuilder()
                    .cacheControl(new CacheControl
                            .Builder()
                            .maxStale(maxStaleConnected, TimeUnit.SECONDS)
                            .build()
                    )
//                    .header("Cache-Control", "max-stale=" + maxStaleConnected)
                    .build();
        }
        return chain.proceed(request);
    }

}
